$(function() {
    // 判断用户是否登录 - 判断cookie中是否存有username
    var username = getCookie('username')
    var login = document.querySelector(".login");
    if (username) {
        var str = `
        <li><a href="">欢太商城APP</a></li>
        <li><a href="javascript:;"><i class="iconfont icon-yonghu"></i><span>${username}</span>
            </a></li>
            <li><a href="javascript:;" class="logout">退出</a></li>
        <li><a href="../html/cart.html"><i class="iconfont icon-gouwuchekong"></i><span>购物车</span><span class="qwe">(0)</span></a></li>
        `
        login.innerHTML = str;
        // 退出功能
        var logout = document.querySelector(".logout");
        logout.onclick = function() {
            layer.confirm('你确定要退出吗？', {
                    btn: ['确定', '取消'] //按钮
                },
                function() {
                    // 删除cookie
                    delCookie('username');
                    login.innerHTML = `
                    <li><a href="">欢太商城APP</a></li>
                    <li><a href="./login.html"><i class="iconfont icon-yonghu"></i><span>登录</span>
                        </a></li>
                    <li><a href="./register.html">注册</a></li>
                    <li><a href="../html/cart.html" class="num"><i class="iconfont icon-gouwuchekong"></i><span>购物车</span><span>0</span></a></li>
                    `
                    var msgindex = layer.msg("退出成功", {
                        icon: 1
                    })
                    setTimeout(function() {
                        layer.close(msgindex)
                        location.href = '../html/list.html';
                    }, 2000)
                },
                function() {
                    layer.msg("已取消", {
                        icon: 1,
                        time: 500
                    })
                    return false;
                }
            );
        }
    } else {
        // 用户没有登录就让用户去登陆
        var msgindex = layer.msg("请先登录", {
            icon: 2,
        })
        setTimeout(function() {
            layer.close(msgindex)
            location.href = 'login.html';
        }, 2000)
    }
    let pro = document.querySelector('#province');
    let city = document.querySelector('#city');
    let area = document.querySelector('#area');
    let town = document.querySelector('#town');
    // pAjax请求获取所有省份并显示
    pAjax({
        url: '../server/province.php',
        dataType: 'json',
        fn: (res) => {
            bindHtml(pro, 'province_id', res, '省份');
            resolve();
        }
    }).then(() => {
        // 给pro一个change事件
        pro.onchange = function() {
            // 获取pid
            let pid = this.value;
            pAjax({
                url: '../server/city.php',
                dataType: 'json',
                data: { pid }, // 简写   
                fn(res) {
                    // 将数据，拼接渲染          
                    bindHtml(city, 'city_id', res, '城市');
                    resolve()
                }
            })
        }
    }).then(() => {
        // 给city一个change事件
        city.onchange = function() {
            // 获取pid
            let cid = this.value;
            pAjax({
                url: '../server/area.php',
                dataType: 'json',
                data: { cid }, // 简写   
                fn(res) {
                    // 将数据，拼接渲染          
                    bindHtml(area, 'area_id', res, '城区');
                    resolve()
                }
            })
        }
    }).then(() => {
        // 给area一个change事件
        area.onchange = function() {
            // 获取pid
            let aid = this.value;
            pAjax({
                url: '../server/town.php',
                dataType: 'json',
                data: { aid }, // 简写   
                fn(res) {
                    // 将数据，拼接渲染          
                    bindHtml(town, 'area_id', res, '城镇街道');
                    resolve()
                }
            })
        }
    })

    function bindHtml(ele, id, res, name) {
        // 将获取到省份加到下拉选框中
        let proStr = `<option value="请选择${name}">请选择${name}</option>`;
        res.forEach(item => {
            proStr += `<option value="${item[id]}">${item['name']}</option>`
        });
        // 将拼接好的标签字符串放到pro标签中
        ele.innerHTML = proStr;
    }
    // ***********************************************四级联动的显示与隐藏
    var cover = document.querySelector('.cover')
    var spans = document.querySelectorAll('.right span');
    // alert(spans)
    spans.forEach(function(item) {
        item.onclick = function() {
            cover.style.display = "block"
        }
    })
    document.querySelector('.cancel').onclick = function() {
        cover.style.display = "none"
    }

    // *************************改变上方购物车的数据
    var username = getCookie('username')
    var data = localStorage.getItem('data');
    var arr = JSON.parse(data);
    var brr = arr.map(v => {
        if (v.username === username) {
            return v.id
        }
    });
    var ids = brr.join(',')
        //   console.log(ids);
    var loadindex = layer.load(0, { shade: true });
    $.ajax({
            url: '../server/cart.php',
            data: { ids },
            dataType: "json",
            success(res) {
                //   console.log(res);
                // var data = res.data
                var { data } = res;
                var str = '';
                //   console.log(data);
                for (var i = 0; i < data.length; i++) {
                    var number = arr.find(v => v.username === username && v.id == data[i].id).num
                    str += `
                <tr valign="bottom">
                    <td><img src="${data[i].imgpath.split('========')[0]}" width="50" height="50"></td>
                    <td>${data[i].h3}</td>
                    <td>x${alll}</td>
                    <td class="price">￥<span>${data[i].price}</span></td>
                </tr>
            `
                }
                $('.table tbody').html(str)
                layer.close(loadindex)
            }
        })
        // alert(data)
    var trr = JSON.parse(data);
    var trr = trr.map(v => {
        if (v.username === username) {
            return v.num
        }
    });
    // alert(trr)
    // console.log(trr);
    var alll = 0;
    for (var i = 0; i < trr.length; i++) {
        alll += parseInt(trr[i])
    }
    // alert($('.login .qwe').text())
    //获取购物车的数量
    $('.login .qwe').text("(" + alll + ")")
        // *********************************改变地址
    $('.cover .save').click(function() {
        var user = document.querySelector('input[name = user]').value
        var phone = document.querySelector('input[name = phone]').value
        let province = $('#province option:selected').text()
        let city = $('#city option:selected').text()
        let area = $('#area option:selected').text()
        let town = $('#town option:selected').text()
        let textarea = $('textarea').val()
        $('.left .user').text(user)
        $('.left .phone').text(phone)
        $('.left .txt').text(province + city + area + town + textarea)
        $('.cover').css('display', 'none')

    })
})